package com.matchmealpha;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityGroup;
import android.app.TabActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TabHost;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

public class MatchMeTabWidget extends TabActivity {

	public static MatchMeTabWidget THIS_INSTANCE;
	public static boolean UPDATING_STATUS;
	public static final String USER_AUTH_FAILURE = "failed: user auth";
	public static final String REQUEST_FAILURE = "failed";
	public static final String REQUEST_SUCCESS = "success";
	public static final String MM_SERVER = "https://matchmeapp.appspot.com/matchmeapp";
	public static final String IMAGE_URL = MM_SERVER + "/show_image";
	public static final String[] FB_PERMISSIONS = new String[] {
			"publish_stream", "read_stream", "offline_access" };

	public static final int RECENT = 1;
	public static final int ALERT = 2;
	public static final int TIMELINE = 3;
	public static final int FRIENDS = 4;
	public static final int SHARE = 5;

	public static final String FACEBOOK_APP_ID = "179372222110397";

	static TabHost tb;

	protected static List<Alert> alertList;
	protected List<Alert> alertListBuffer;
	protected static AlertListAdapter alertAdapter;

	protected static List<String> friendsList;

	protected static List<Post> timelineList;
	protected List<Post> timelineBuffer;
	protected static TimelineListAdapter timelineAdapter;

	protected static List<String> findFriendsList;
	protected static FriendsListAdapter friendsAdapter;

	protected static List<Post> recentList;
	protected List<Post> recentListBuffer;
	protected static RecentListAdapter recentAdapter;

	protected static Facebook mFacebook;
	protected static AsyncFacebookRunner mAsyncRunner;

	private static String  sessionid;
	private String username;

	private Handler mHandler = new Handler();
	private Runnable mUpdateTask = new UpdateUITaskClass();
	TimerTask updateTimerTask;

	public void onCreate(Bundle savedInstanceState) {
		THIS_INSTANCE = this;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_layout_view);

		SharedPreferences settings = getSharedPreferences(
				"matchme_preferences", 0);
		sessionid = settings.getString("sessionid", "");
		username = settings.getString("username", "");

		Resources res = getResources(); // Resource object to get Drawables
		TabHost tabHost = getTabHost(); // The activity TabHost
		TabHost.TabSpec spec; // Resusable TabSpec for each tab
		Intent intent; // Reusable Intent for each tab
		tb = tabHost;

		final InstanceDataObject data = (InstanceDataObject) getLastNonConfigurationInstance();
		/*****************************************************/
		/* FACEBOOK */
		/*****************************************************/
		mFacebook = new Facebook(MatchMeTabWidget.FACEBOOK_APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);

		if (data != null) {
			Log.d("HELLO", "IN HERE: not null");
			alertList = data.alertList;
			alertListBuffer = data.alertListBuffer;
			friendsList = data.friendsList;
			timelineList = data.timelineList;
			timelineBuffer = data.timelineListBuffer;
			findFriendsList = data.findFriendsList;
			recentList = data.recentList;
			recentListBuffer = data.recentListBuffer;

		} else {

			alertList = new ArrayList<Alert>();
			alertListBuffer = new ArrayList<Alert>();
			friendsList = new ArrayList<String>();
			timelineList = new ArrayList<Post>();
			timelineBuffer = new ArrayList<Post>();
			findFriendsList = null;
			recentList = new ArrayList<Post>();
			recentListBuffer = new ArrayList<Post>();

			// mytimeline
			 updateTimerTask = new UpdateTaskClass();
             Timer checkForUpdatesTimer = new Timer("CheckForUpdatesTimer", false);
		     checkForUpdatesTimer.schedule(updateTimerTask, 0, 60000);

			// new MyTimelineTask().execute(0 + "");
			// new MyRecentTask().execute(0 + "");
			new MyFriendsListTask().execute();
			// new MyAlertTask().execute();
		}

		intent = new Intent().setClass(this, AlertGroup.class);
		spec = tabHost.newTabSpec("alerts").setIndicator("Alerts").setContent(
				intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, RecentGroup.class);
		spec = tabHost.newTabSpec("recent").setIndicator("Recent").setContent(
				intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, ShareActivity.class);
		spec = tabHost.newTabSpec("share").setIndicator("Share").setContent(
				intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, TimelineGroup.class);
		spec = tabHost.newTabSpec("timeline").setIndicator("Timeline")
				.setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, FriendsListGroup.class);
		spec = tabHost.newTabSpec("friends").setIndicator("Friends")
				.setContent(intent);
		tabHost.addTab(spec);

		tabHost.setCurrentTab(3);


		// mytimeline
		// new MyTimelineTask().execute(0 + "");

		// mHandler.removeCallbacks(mUpdateTask);
		// mHandler.postDelayed(mUpdateTask, 60000);
	}

	public static TabHost myTabHost() {
		return tb;
	}

	public static void myReplaceView(View v, int callerID) {
		switch (callerID) {
		case (1):
			RecentGroup.recentGroup.replaceView(v);
			break;
		case (2):
			AlertGroup.alertGroup.replaceView(v);
			break;
		case (3):
			TimelineGroup.timelineGroup.replaceView(v);
			break;
		case (4):
			FriendsListGroup.friendsListGroup.replaceView(v);
			break;
		}
	}

	public static ActivityGroup getCurrGroup(int callerID) {
		switch (callerID) {
		case (1):
			return RecentGroup.recentGroup;
		case (2):
			return AlertGroup.alertGroup;
		case (3):
			return TimelineGroup.timelineGroup;
		case (4):
			return FriendsListGroup.friendsListGroup;
		}
		return null;
	}

	public static ArrayList<View> getHistory(int callerID) {
		switch (callerID) {
		case (1):
			return RecentGroup.recentGroup.getHistory();
		case (2):
			return AlertGroup.alertGroup.getHistory();
		case (3):
			return TimelineGroup.timelineGroup.getHistory();
		case (4):
			return FriendsListGroup.friendsListGroup.getHistory();
		}
		return null;
	}

	public static void myBack(int callerID) {
		switch (callerID) {
		case (1):
			RecentGroup.recentGroup.back();
			break;
		case (2):
			AlertGroup.alertGroup.back();
			break;
		case (3):
			TimelineGroup.timelineGroup.back();
			break;
		case (4):
			FriendsListGroup.friendsListGroup.back();
			break;
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		InstanceDataObject ido = new InstanceDataObject();
		// Log.d("SIZE", timelineList.size() + "");
		ido.alertList = alertList;
		ido.alertListBuffer = alertListBuffer;
		ido.friendsList = friendsList;
		//ido.friendsListBuffer = friendsListBuffer;
		ido.timelineList = timelineList;
		ido.timelineListBuffer = timelineBuffer;
		ido.findFriendsList = findFriendsList;
		ido.recentList = recentList;
		ido.recentListBuffer = recentListBuffer;
		return ido;
	}

	private class MyTimelineTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {
			TimelineActivity.CURRENTLY_DOWNLOADING = true;
			HttpRequest req = new HttpRequest(sessionid);
			String response;
			// if (relationship) {
			// response = req.sendPost(MatchMeTabWidget.MM_SERVER
			// + "/get_relationship/" + curruser + "/" + listingOrder,
			// "");
			// } else {
			response = req.sendPost(MatchMeTabWidget.MM_SERVER
					+ "/get_timeline/" + data[0], "");
			// }
			if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response)
					|| MatchMeTabWidget.REQUEST_FAILURE.equals(response))
				return false;
			else if (response != null) {
				Scanner in = new Scanner(response).useDelimiter(";");
				Post post;
				while (in.hasNext()) {
					post = new Post();
					post.setPostID(in.nextInt());
					post.setUserID1(in.next());
					post.setUserID2(in.next());
					post.setLocation1(in.next());
					post.setLocation2(in.next());
					post.setStatus(in.next());
					post.setTime1(in.next());
					post.setTime2(in.next());
					post.setDescription1(in.next());
					post.setDescription2(in.next());
					//ShareActivity.getPostImage(post, sessionid);
					ShareActivity.getPostBitMapImage(post,sessionid);
					timelineList.add(post);
					publishProgress();
				}
				return true;
			} else
				return false;
		}

		protected void onProgressUpdate(Void... values) {
			Log.d("UPDATE TIMELINE", "UPDATE");

			if (timelineAdapter != null) {

				timelineAdapter.notifyDataSetChanged();
			}
		}

		protected void onPostExecute(Boolean result) {
			Log.d("UPDATE TIMELINE", "Done");
			TimelineActivity.CURRENTLY_DOWNLOADING = false;
			if (TimelineActivity.ACTIVE_INSTANCE != null) {
				TimelineActivity.ACTIVE_INSTANCE.hideLoadingPanel();

			}
			if (result) {
				if (timelineAdapter != null) {

					timelineAdapter.notifyDataSetChanged();
				}
				if (timelineList.size() <= 0) {
					Toast.makeText(MatchMeTabWidget.this, "No Image Found.",
							Toast.LENGTH_LONG);
				}
			} else {
				// errorMsg.setText("Unable to connect. Please try again");

			}
		}

	}

	private class MyRecentTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {
			RecentActivity.CURRENTLY_DOWNLOADING = true;
			HttpRequest req = new HttpRequest(sessionid);
			String response;
			response = req.sendPost(MatchMeTabWidget.MM_SERVER + "/get_recent/"
					+ data[0], "");
			if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response)
					|| MatchMeTabWidget.REQUEST_FAILURE.equals(response))
				return false;
			else if (response != null) {
				if (response != "") {
					Scanner in = new Scanner(response).useDelimiter(";");
					Post post;
					recentList.clear();
					while (in.hasNext()) {
						post = new Post();
						post.setPostID(in.nextInt());
						post.setUserID1(in.next());
						post.setUserID2(in.next());
						post.setLocation1(in.next());
						post.setLocation2(in.next());
						post.setStatus(in.next());
						post.setTime1(in.next());
						post.setTime2(in.next());
						post.setDescription1(in.next());
						post.setDescription2(in.next());
						//ShareActivity.getPostImage(post, sessionid);
						ShareActivity.getPostBitMapImage(post,sessionid);
						recentList.add(post);
						publishProgress();
					}
				}
				return true;
			} else
				return false;
		}

		protected void onProgressUpdate(Void... values) {

			if (recentAdapter != null) {

				recentAdapter.notifyDataSetChanged();
			}
		}

		protected void onPostExecute(Boolean result) {
			RecentActivity.CURRENTLY_DOWNLOADING = false;
			if (RecentActivity.ACTIVE_INSTANCE != null) {
				RecentActivity.ACTIVE_INSTANCE.hideLoadingPanel();

			}
			if (result) {
				if (recentList.size() <= 0) {
					Toast.makeText(MatchMeTabWidget.this,
							"No Recent Images Found", Toast.LENGTH_LONG);
				}
			} else {
				// errorMsg.setText("Unable to connect. Please try again");
			}
		}
		// leftButton.setVisibility(View.INVISIBLE);
		// rightButton.setVisibility(View.INVISIBLE);
	}

	private class MyFriendsListTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {
			FriendsListActivity.CURRENTLY_DOWNLOADING = true;
			HttpRequest req = new HttpRequest(sessionid);
			String response;
			response = req.sendPost(
					MatchMeTabWidget.MM_SERVER + "/get_friends", "");
			if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response))
				return false;
			else if (response != "") {
				Scanner in = new Scanner(response).useDelimiter(";");
				String str;
				friendsList.clear();
				while (in.hasNext()) {
					str = in.next();
					friendsList.add(str);
					publishProgress();
				}
				return true;
			} else
				return false;
		}

		protected void onProgressUpdate(Void... values) {

			if (friendsAdapter != null) {

				friendsAdapter.notifyDataSetChanged();
			}
		}

		protected void onPostExecute(Boolean result) {
			// loadingDialog.cancel();
			FriendsListActivity.CURRENTLY_DOWNLOADING = false;
			if (FriendsListActivity.ACTIVE_INSTANCE != null) {
				FriendsListActivity.ACTIVE_INSTANCE.hideLoadingPanel();

			}
			if (result) {
				if (friendsList.size() <= 0) {
					Toast.makeText(MatchMeTabWidget.this,
							"You currently have no friends", Toast.LENGTH_LONG);
				}
				// displayLayout();
			} else {
				// errorMsg.setText("Unable to connect. Please try again");
				// displayErrorLayout();
			}
		}
	}

	private class MyAlertTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {
			AlertActivity.CURRENTLY_DOWNLOADING = true;
			HttpRequest req = new HttpRequest(sessionid);
			String response;
			response = req.sendPost(MatchMeTabWidget.MM_SERVER + "/get_alerts",
					"");
			if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response))
				return false;
			else if (response != null) {
				Scanner in = new Scanner(response).useDelimiter(";");
				Alert alt;
				alertList.clear();
				while (in.hasNext()) {
					alt = new Alert();
					alt.setAlertID(in.nextInt());
					alt.setUserID1(username);
					alt.setUserID2(in.next());
					alt.setType(in.next().toCharArray()[0]);
					alt.setTypeID(in.nextInt());
					alt.setCreated(in.next());
					alertList.add(alt);
					publishProgress();
				}
				return true;
			} else
				return false;
		}

		protected void onProgressUpdate(Void... values) {

			if (alertAdapter != null) {

				alertAdapter.notifyDataSetChanged();
			}
		}

		protected void onPostExecute(Boolean result) {
			AlertActivity.CURRENTLY_DOWNLOADING = false;
			if (AlertActivity.ACTIVE_INSTANCE != null) {
				AlertActivity.ACTIVE_INSTANCE.hideLoadingPanel();

			}
			if (result) {
				if (alertList.size() <= 0) {
					Toast.makeText(MatchMeTabWidget.this, "No New Alert",
							Toast.LENGTH_LONG);
				}
				// displayLayout();
			} else {
				// errorMsg.setText("Unable to connect. Please try again");
				// displayErrorLayout();
			}
		}
	}

	private class UpdateTaskClass extends TimerTask {

		@Override
		public void run() {
			if(!MatchMeTabWidget.UPDATING_STATUS)
			{
			MatchMeTabWidget.UPDATING_STATUS = true;
			Log.d("IN UPDATE HANDLER", "K");
			// retrieve latest post
			RecentActivity.CURRENTLY_DOWNLOADING = true;
			TimelineActivity.CURRENTLY_DOWNLOADING = true;
			AlertActivity.CURRENTLY_DOWNLOADING = true;

			mHandler.removeCallbacks(mUpdateTask);
			mHandler.postDelayed(mUpdateTask, 200);

			String postDate = "";
			// Collections.sort(timelineList);
			// Collections.reverse(timelineList);
			timelineBuffer.clear();
			if (timelineList.size() > 0) {
				GregorianCalendar d = timelineList.get(0).getDate();
				Log.d("NEWEST", d.toString());
				postDate = "" + d.get(Calendar.YEAR) + "-"
						+ d.get(Calendar.MONTH) + "-"
						+ d.get(Calendar.DAY_OF_MONTH) + "-"
						+ d.get(Calendar.HOUR_OF_DAY) + "-"
						+ d.get(Calendar.MINUTE) + "-"
						+ (d.get(Calendar.SECOND) + 1);

			} else {
				postDate = "1-1-1-0-0-0";
			}

			// retrieve list of recent Posts Id's
			String recentDate = "";
			// Collections.sort(recentList);
			// Collections.reverse(recentList);
			recentListBuffer.clear();
			if (recentList.size() > 0) {
				GregorianCalendar d = recentList.get(0).getDate();
				recentDate = "" + d.get(Calendar.YEAR) + "-"
						+ d.get(Calendar.MONTH) + "-"
						+ d.get(Calendar.DAY_OF_MONTH) + "-"
						+ d.get(Calendar.HOUR_OF_DAY) + "-"
						+ d.get(Calendar.MINUTE) + "-"
						+ (d.get(Calendar.SECOND) + 1);

			} else {
				recentDate = "1-1-1-0-0-0";
			}

			// retrieve list of current Alert id's
			String alertDate = "";
			// Collections.sort(alertList);
			// Collections.reverse(alertList);
			alertListBuffer.clear();
			if (alertList.size() > 0) {
				GregorianCalendar d = alertList.get(0).getCreated();
				alertDate = "" + d.get(Calendar.YEAR) + "-"
						+ d.get(Calendar.MONTH) + "-"
						+ d.get(Calendar.DAY_OF_MONTH) + "-"
						+ d.get(Calendar.HOUR_OF_DAY) + "-"
						+ d.get(Calendar.MINUTE) + "-"
						+ (d.get(Calendar.SECOND) + 1);
			} else {
				alertDate = "1-1-1-0-0-0";
			}

			// timeline
			HttpRequest req;
			String response;

			if (!("".equals(postDate))) {
				req = new HttpRequest(sessionid);
				response = req.sendPost(MatchMeTabWidget.MM_SERVER
						+ "/get_timeline_latest/" + postDate, "");

				Scanner in = new Scanner(response).useDelimiter(";");
				Post post;
				while (in.hasNext()) {
					post = new Post();
					post.setPostID(in.nextInt());
					post.setUserID1(in.next());
					post.setUserID2(in.next());
					post.setLocation1(in.next());
					post.setLocation2(in.next());
					post.setStatus(in.next());
					post.setTime1(in.next());
					post.setTime2(in.next());
					post.setDescription1(in.next());
					post.setDescription2(in.next());
					ShareActivity.getPostImage(post, sessionid);
					timelineBuffer.add(0, post);

					mHandler.removeCallbacks(mUpdateTask);
					mHandler.postDelayed(mUpdateTask, 200);
				}

				TimelineActivity.CURRENTLY_DOWNLOADING = false;
				mHandler.removeCallbacks(mUpdateTask);
				mHandler.postDelayed(mUpdateTask, 200);

			}

			// recent//
			if (!("".equals(recentDate))) {
				req = new HttpRequest(sessionid);
				response = req.sendPost(MatchMeTabWidget.MM_SERVER
						+ "/get_recent_latest/" + recentDate, "");
				Scanner in = new Scanner(response).useDelimiter(";");
				Post post;

				while (in.hasNext()) {
					post = new Post();
					post.setPostID(in.nextInt());
					post.setUserID1(in.next());
					post.setUserID2(in.next());
					post.setLocation1(in.next());
					post.setLocation2(in.next());
					post.setStatus(in.next());
					post.setTime1(in.next());
					post.setTime2(in.next());
					post.setDescription1(in.next());
					post.setDescription2(in.next());
					ShareActivity.getPostImage(post, sessionid);
					recentListBuffer.add(0, post);

					mHandler.removeCallbacks(mUpdateTask);
					mHandler.postDelayed(mUpdateTask, 200);
				}

				RecentActivity.CURRENTLY_DOWNLOADING = false;
				mHandler.removeCallbacks(mUpdateTask);
				mHandler.postDelayed(mUpdateTask, 200);
			}

			// alert//

			if (!("".equals(alertDate))) {
				req = new HttpRequest(sessionid);
				response = req.sendPost(MatchMeTabWidget.MM_SERVER
						+ "/get_alerts_latest/" + alertDate, "");

				Scanner in = new Scanner(response).useDelimiter(";");
				Alert alt;
				while (in.hasNext()) {
					alt = new Alert();
					alt.setAlertID(in.nextInt());
					alt.setUserID1(username);
					alt.setUserID2(in.next());
					alt.setType(in.next().toCharArray()[0]);
					alt.setTypeID(in.nextInt());
					alt.setCreated(in.next());
					alertListBuffer.add(0, alt);

					mHandler.removeCallbacks(mUpdateTask);
					mHandler.postDelayed(mUpdateTask, 200);
				}

				AlertActivity.CURRENTLY_DOWNLOADING = false;
				mHandler.removeCallbacks(mUpdateTask);
				mHandler.postDelayed(mUpdateTask, 200);
			}

			mHandler.removeCallbacks(mUpdateTask);
			mHandler.postDelayed(mUpdateTask, 200);

			// mHandler.postAtTime(this,
			// System.currentTimeMillis() + 30000);
			MatchMeTabWidget.UPDATING_STATUS = false;

		}
		}

	}

	private class UpdateUITaskClass implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub

			if (AlertActivity.CURRENTLY_DOWNLOADING) {
				if (AlertActivity.ACTIVE_INSTANCE != null) {
					AlertActivity.ACTIVE_INSTANCE.showLoadingPanel();
				}
			} else {
				if (AlertActivity.ACTIVE_INSTANCE != null) {
					AlertActivity.ACTIVE_INSTANCE.hideLoadingPanel();
				}
			}

			if (RecentActivity.CURRENTLY_DOWNLOADING) {
				if (RecentActivity.ACTIVE_INSTANCE != null) {
					RecentActivity.ACTIVE_INSTANCE.showLoadingPanel();
				}
			} else {
				if (RecentActivity.ACTIVE_INSTANCE != null) {
					RecentActivity.ACTIVE_INSTANCE.hideLoadingPanel();
				}

			}

			if (TimelineActivity.CURRENTLY_DOWNLOADING) {
				if (TimelineActivity.ACTIVE_INSTANCE != null) {
					TimelineActivity.ACTIVE_INSTANCE.showLoadingPanel();
				}
			} else {
				if (TimelineActivity.ACTIVE_INSTANCE != null) {
					TimelineActivity.ACTIVE_INSTANCE.hideLoadingPanel();
				}

			}

			// can be removed when posts are returned in order
			Collections.sort(recentList);
			Collections.reverse(recentList);
			recentList.addAll(0, recentListBuffer);
			recentListBuffer.clear();
			if (recentList.size() > 10) {
				recentList.remove(recentList.size() - 1);
			}
			// timelineList.subList(start, end)
			if (recentAdapter != null) {

				recentAdapter.notifyDataSetChanged();
			}

			// can be removed when posts are returned in order
			Collections.sort(alertList);
			Collections.reverse(alertList);
			alertList.addAll(0, alertListBuffer);
			alertListBuffer.clear();
			if (alertAdapter != null) {

				alertAdapter.notifyDataSetChanged();
			}

			// can be removed when posts are returned in order
			Collections.sort(timelineList);
			Collections.reverse(timelineList);
			timelineList.addAll(0, timelineBuffer);
			if (timelineList.size() > 10) {
				timelineList.remove(timelineList.size() - 1);
			}
			timelineBuffer.clear();
			if (timelineAdapter != null) {

				timelineAdapter.notifyDataSetChanged();
			}

		}

	}

	protected static int[] byteToIntArray(byte[] arr) {
		int[] returnVal = new int[arr.length / 4];
		for (int i = 0; i < returnVal.length; i++) {
			returnVal[i] = byteArrayToInt(arr, i * 4);
		}
		return returnVal;
	}

	protected static int byteArrayToInt(byte[] b, int offset) {
		int value = 0;
		for (int i = 0; i < 4; i++) {
			int shift = (4 - 1 - i) * 8;
			value += (b[i + offset] & 0x000000FF) << shift;
		}
		return value;
	}
	
	protected static byte[] intArrayToByte(int[] arr){
		byte[] barray = new byte[arr.length*4];
		for (int i = 0; i < arr.length; i++) {
			barray[i*4] = (byte) (arr[i] >> 24);
			barray[i*4 + 1] = (byte) (arr[i] >> 16);
			barray[i*4 + 2] = (byte) (arr[i] >> 8);
			barray[i*4 + 3] = (byte) (arr[i] >> 0);
		}
		return barray;
	}
	
	
}
